<template>
    <el-card class="box-card" shadow="never">
      <div slot="header" class="clearfix">
        <h3>更换头像</h3>
      </div>
      <div class="block"><el-avatar shape="square" :size="250" :src="avatar" fit="cover">选择头像</el-avatar></div>
      <el-button @click="userimg" size="medium" type="primary"><i class="el-icon-plus"></i>选择封面</el-button>
      <el-button @click="patchuser" size="medium" type="primary" plain ><i class="el-icon-upload2"></i>上传头像</el-button>
      <input type="file" ref="select" @change="showImg" accept="image/*" style="display:none">

    </el-card>
</template>

<script>
import { patchuser, getuser } from '@/api/user'
import { mapGetters } from 'vuex'
export default {
  name: 'BigEventIndex',

  data () {
    return {
      avatar: ''
    }
  },

  mounted () {
    this.avatar = this.getUserInfo().user_pic
  },

  methods: {
    ...mapGetters(['getUserInfo']),

    userimg () {
      this.$refs.select.click()
    },
    showImg (e) {
      if (e.target.files.length === 0) {
        // 点击了取消了,就恢复默认图片
        this.avatar = ''
      } else {
        // FileReader 浏览器提供的方法
        const reader = new FileReader()
        // reader里面有个方法readAsDataURL 可以将图片转base64进制
        reader.readAsDataURL(e.target.files[0])
        // onload可以监听转换完成后
        reader.onload = () => {
          // 给声明变量赋值
          this.avatar = reader.result
        }
      }
    },
    // 点击上传头像
    async  patchuser () {
      // 发送axios 上传
      const { data: res } = await patchuser({ avatar: this.avatar })
      // 判断业务状态码是否上传成功给出提示
      if (res.code !== 0) return this.$message.error(res.message)
      this.$message.success(res.message)
      // 上传成功发送重新发送axios获取最新用户信息
      const { data } = await getuser()
      this.$store.commit('setUserInfo', data.data)
    }
  }
}

</script>

<style lang="less" scoped>
.el-button {
  margin-top: 2rem;
  margin-right: 1rem ;
}

</style>
